package com.heba.fragment.scan;

import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.heba.Cfg;
import com.heba.config.CommonConfig;
import com.heba.dialog.CustomDialogView;
import com.heba.event.MessageEvent;
import com.heba.fragment.BaseFragment;
import com.heba.greenmulu.R;
import com.heba.greenmulu.scan.ItemAddProductActivity;
import com.heba.greenmulu.scan.ItemProductDetailActivity;
import com.heba.helper.MemberShipHelper;
import com.heba.utils.ToastShow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.bingoogolapple.qrcode.core.BarcodeType;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zbar.ZBarView;

/**
 * BarScanFragment
 * Created by jason on 2019/4/16.
 */
public class BarScanFragment extends BaseFragment implements QRCodeView.Delegate {

    private View scanView;
    private View stopView;
    private TextView tvScan;
    private ZBarView mZBarView;

    private boolean openScan = false;  //是否开启扫描预览

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //注册eventBus
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_bar_scan, null);
        scanView = view.findViewById(R.id.rl_view);
        stopView = view.findViewById(R.id.ll_view);
        tvScan = view.findViewById(R.id.tv_scan);
        tvScan.setForceDarkAllowed(false);
        mZBarView = view.findViewById(R.id.zbarview);
        mZBarView.setDelegate(this);
        mZBarView.setType(BarcodeType.ONE_DIMENSION, null);
        showCamera();

        tvScan.setOnClickListener(v -> {
            if (!openScan) {
                openScan = true;
                showCamera();
            } else {
                openScan = false;
                stopCamera();
            }
        });
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
//        mZBarView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
////        mZBarView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别
//        mZBarView.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }

    @Override
    public void onStop() {
        super.onStop();
//        mZBarView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        /**
         * 接收事件
         */
        switch (event.getEvent()) {
            case CommonConfig.SCAN_VISIBLE:
                showCamera();
                break;
            case CommonConfig.SCAN_HIDDEN:
                openScan = false;
                stopCamera();
                break;
            case CommonConfig.SCAN_MY_PRODUCT:
            case CommonConfig.SCAN_HISTORY:
            case CommonConfig.SCAN_REFRESH:
                if (openScan) {
                    openScan = false;
                    stopCamera();
                }
//                    mZBarView.stopSpot();  //停止识别
                break;
            case CommonConfig.SCAN_BAR_SCAN:
//                if (openScan){
//                    openScan = false;
//                    stopCamera();
//                }
//                mZBarView.startSpot();  //开始识别
                break;
            default:
                break;
        }
    }

    /**
     * 显示扫描view或停止扫描view
     */
    private void checkScanView() {
        if (!openScan) {
            scanView.setVisibility(View.GONE);
            stopView.setVisibility(View.VISIBLE);
            tvScan.setSelected(false);
            tvScan.setText(getResources().getString(R.string.scan_start));
        } else {
            scanView.setVisibility(View.VISIBLE);
            stopView.setVisibility(View.GONE);
            tvScan.setSelected(true);
            tvScan.setText(getResources().getString(R.string.scan_stop));
        }
    }

    /**
     * 显示扫描框并开始识别
     */
    private void showCamera() {
        if (Cfg.isNeedToReleaseCamera) {
            mZBarView.stopCamera();
            Cfg.isNeedToReleaseCamera = false;
        }

        checkScanView();
        if (!openScan) {
            return;
        }
        mZBarView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
//              mZBarView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别
        mZBarView.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }

    /**
     * 关闭摄像头并隐藏扫描框
     */
    private void stopCamera() {
        checkScanView();
        mZBarView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
    }

    @Override
    public void onDestroy() {
        //解除注册
        EventBus.getDefault().unregister(this);
        mZBarView.onDestroy(); // 销毁二维码扫描控件
        super.onDestroy();
    }

    /**
     * 震动
     */
    private void vibrate() {
        Vibrator vibrator = (Vibrator) getActivity().getSystemService(getActivity().VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        Log.i("onScanQRCodeSuccess", "result:" + result);

        //震动
        vibrate();

        /**
         * 延迟5秒可以继续扫描
         */
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mZBarView.startSpot(); // 开始识别
            }
        }, 5000);

        /**
         * 处理扫描结果
         */
        progressDialog.show();
        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
            @Override
            public void Success() {
                progressDialog.dismiss();
                if (Cfg.isProduct) {
                    //存在产品，则跳转到产品详情页面
                    Bundle bundle = new Bundle();
                    bundle.putString(CommonConfig.BARCODE, result);
//                    openActivity(ItemComparisoActivity.class, bundle);
                    openActivity(ItemProductDetailActivity.class, bundle);
//                    ToastShow.displayToast(getActivity(), "Scan Result:" + result);
                } else {
                    //不存在产品，则跳转到新增产品页面
                    new CustomDialogView(new CustomDialogView.OnCustomDialogClickListener() {
                        @Override
                        public void onYesClick() {
                            Bundle bundle = new Bundle();
                            bundle.putString(CommonConfig.BARCODE, result);
                            openActivity(ItemAddProductActivity.class, bundle);
                        }

                        @Override
                        public void onNoClick() {

                        }
                    }).showDialog(getActivity(), getActivity().getResources().getString(R.string.please_add_product), "");
                }
            }

            @Override
            public void Fail(String error) {
                progressDialog.dismiss();
            }
        }).getBarCodeScanResult(getActivity(), result);

    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
//        String tipText = mZBarView.getScanBoxView().getTipText();
//        String ambientBrightnessTip = "\n环境过暗，请打开闪光灯";
//        if (isDark) {
//            if (!tipText.contains(ambientBrightnessTip)) {
//                mZBarView.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
//            }
//        } else {
//            if (tipText.contains(ambientBrightnessTip)) {
//                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
//                mZBarView.getScanBoxView().setTipText(tipText);
//            }
//        }
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Log.e("OpenCameraError", "打开相机出错");
        ToastShow.displayToast(getActivity(), getResources().getString(R.string.camera_failure));
    }
}
